clear;clear;clear;clear;clear;clear;
clc;
%% create session, connect devices
session=MeasurementSession.SimpleMeasurement([Constant.AutoMeasurementRootPath '/example/DemodPhase/device.dat']);

probe_eater_volt = 0:0.025:0.9;
result = cell(1, length(probe_eater_volt));
for k = 1:length(probe_eater_volt)
    ziDAQ('setDouble', '/dev3543/auxouts/0/offset', probe_eater_volt(k) );

    %% phase calibration
    ziDAQ('setInt', '/dev3560/sigouts/0/enables/2', 0); pause(3);
    phaseCalibration = adjustPhase(session);

    %% get Spectrum
    ziDAQ('setInt', '/dev3560/sigouts/0/enables/2', 1); pause(30);
    ch = '3'; lpOrder = 3; lpBW = 100; freqSpan = 400.0; nFreq=2048; average = 100;
    spectrum = getSpectrum('dev3543', ch, lpOrder, lpBW, freqSpan, nFreq, average);
    
    %% store
    result{k}.probe_eaater_volt = probe_eater_volt(k);
    result{k}.phaseCalData = phaseCalibration;
    result{k}.spectrum = spectrum;
end

%% plot
for k=1:length(probe_eater_volt)
    plotSpectrum(result{k}.spectrum.dev3543.demods(4).sample_x_fft_abs_avg{1});
    hold on;
end

figure;

bgRange = 100:200; peakPos = 221;
bgNoise=zeros(1, length(probe_eater_volt));
pkValue=zeros(1, length(probe_eater_volt));
for k=1:length(probe_eater_volt)
    bgNoise(k) = mean(result{k}.spectrum.dev3543.demods(4).sample_x_fft_abs_avg{1}.value(bgRange));
    pkValue(k) = result{k}.spectrum.dev3543.demods(4).sample_x_fft_abs_avg{1}.value(peakPos);
end

subplot(2, 1, 1)
plot(probe_eater_volt, bgNoise, 'bo-')
ylim([1e-4 1.2e-3])
xlabel('probe eater voltage (V)','Interpreter','latex');
ylabel('background noise (V/Hz$^{1/2}$)','Interpreter','latex');
grid on
subplot(2, 1, 2)
plot(probe_eater_volt, pkValue, 'rd-')
ylim([1e-1 1.2])
xlabel('probe eater voltage (V)','Interpreter','latex');
ylabel('Peak Value (V/Hz$^{1/2}$)','Interpreter','latex');
grid on

%%
save('D:\code\AutoMeasurement\example\DemodPhase\ProbePower.mat', 'result');